<?php

declare(strict_types=1);

namespace app\controller\trade;

use app\BaseController;
use app\model\Order as OrderModel;
use app\service\factory\ResponseFactory;
use app\service\order\OrderService;
use think\Response;
use Throwable;

class Order extends BaseController
{
    public function index(OrderService $orderService): Response
    {
        try {
            $page = max(1, (int) $this->request->param('page', 1));
            $pageSize = (int) $this->request->param('page_size', 20);
            $pageSize = $pageSize > 0 ? min($pageSize, 100) : 20;

            $filters = $this->request->only([
                'keyword',
                'status',
                'pay_status',
                'ship_status',
                'refund_status',
                'finish_status',
                'audit_status',
                'buyer_org_id',
                'seller_org_id',
                'assist_user_id',
                'start_time',
                'end_time',
            ], 'get');

            $paginator = $orderService->paginate($filters, $page, $pageSize);
            $list = array_map(function (OrderModel $order) {
                return $this->formatListItem($order);
            }, $paginator->items());

            return json(ResponseFactory::paginated(
                $list,
                (int) $paginator->total(),
                $page,
                $pageSize
            ));
        } catch (Throwable $e) {
            return json(ResponseFactory::error($e->getMessage(), $e->getCode() ?: 500));
        }
    }

    public function read(int $id, OrderService $orderService): Response
    {
        try {
            $order = $orderService->findById($id);
            if (!$order) {
                return json(ResponseFactory::error('订单不存在', 404));
            }

            return json(ResponseFactory::success([
                'info' => $orderService->format($order),
            ]));
        } catch (Throwable $e) {
            return json(ResponseFactory::error($e->getMessage(), $e->getCode() ?: 500));
        }
    }

    private function formatListItem(OrderModel $order): array
    {
        $items = $order->items ? $order->items->all() : [];

        return [
            'id' => (int) $order->id,
            'order_no' => $order->order_no,
            'status' => (int) $order->status,
            'buyer_org_id' => $order->buyer_org_id ? (int) $order->buyer_org_id : null,
            'seller_org_id' => $order->seller_org_id ? (int) $order->seller_org_id : null,
            'product_amount' => count($items),
            'original_total_amount' => (float) $order->buyer_payable_amount,
            'buyer_remark' => $order->buyer_remark,
            'seller_remark' => $order->seller_remark,
            'create_time' => $order->create_time,
            'update_time' => $order->update_time,
        ];
    }
}
